import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth' // 从 Cookie 里拿到token
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })

let hasRoles = true

const whiteList = ['/login', '/register']

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // 设置页面title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // 调用获取信息的action，重新获取动态路由   (防止页面刷新出现白屏)
      await store.dispatch('user/getInfo')
      // 拿到动态添加的路由
      const routes = store.state.user.resultAllRoutes
      if (hasRoles) {
        // 重新添加动态路由
        router.addRoutes(routes)
        hasRoles = false
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
